﻿using jvm.instructions.common;
using jvm.rtda;
using jvm.rtda.frame;
using jvm.rtda.heap;
using jvm.rtda.heap.clazz;
using jvm.rtda.heap.clazz.cp;
using jvm.rtda.heap.pool;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace jvm.instructions.constants
{
    class LdcUtil
    {
        public static void _ldc(JFrame frame, uint index)
        {
            JOperandStack stack = frame.operandStack;
            JClass jClass = frame.method.jClass;
            JConstantPool pool = jClass.constantPool;
            object obj = pool.GetConstant<object>(index);
            if (obj.GetType() == typeof(int))
                stack.PushInt((int)obj);
            else if (obj.GetType() == typeof(float))
                stack.PushFloat((float)obj);
            else if (obj.GetType() == typeof(string))
                stack.PushRef(StringPool.StringObject(jClass.loader, (string)obj));
            else if (obj.GetType() == typeof(ClassRef))
            {
                ClassRef classRef = (ClassRef)obj;
                stack.PushRef(classRef.ResolvedClass().jLClassObject);
            }
            else
            {
                // todo
                Console.WriteLine("todo ldc");
                Environment.Exit(0);
            }
        }
    }

    class LDC : Index8Instruction
    {
        public override void Execute(JFrame frame)
        {
            LdcUtil._ldc(frame, index);
        }
    }

    class LDC_W : Index16Instruction
    {
        public override void Execute(JFrame frame)
        {
            LdcUtil._ldc(frame, index);
        }
    }

    class LDC2_W : Index16Instruction
    {
        public override void Execute(JFrame frame)
        {
            JOperandStack stack = frame.operandStack;
            JConstantPool pool = frame.method.jClass.constantPool;
            object obj = pool.GetConstant<object>(index);
            if (obj.GetType() == typeof(long))
                stack.PushLong((long)obj);
            else if (obj.GetType() == typeof(double))
                stack.PushDouble((double)obj);
            else
            {
                // todo
                Console.WriteLine("java.lang.ClassFormatError");
                Environment.Exit(0);
            }
        }
    }
}
